#include <stdio.h>
#include "zip.h"

int main( int argc, char **argv ) {

  FILE *fp ;
  ZIP_END_HEADER zip_end_header ;
  ZIP_CENTRAL_HEADER zip_central_header ;
  unsigned int i, j ;
  char zip_end_header_signature[] = { 0x50, 0x4b, 0x05, 0x06 } ;
 
  if( argc != 2 ) {
    printf( "usage : %s <filename>\n", argv[ 0 ] ) ;
    return -1 ;
  }

  if( ! ( fp = fopen( argv[ 1 ], "rb" ) ) ) {
    printf( "failed to open input file.\n" ) ;
    return -1 ;
  }

  if( fseek( fp, - SIZEOF_ZIP_END_HEADER, SEEK_END ) ) {
    printf( "failed to seek input file.\n" ) ;
    return -1 ;
  }

  if( ! fread( &zip_end_header, SIZEOF_ZIP_END_HEADER, 1, fp ) ) {
    printf( "failed to read input file.\n" ) ;
    return -1 ;
  }

  for( i = 0; i < 4; i++ ) {
    if( zip_end_header.signature[i] != zip_end_header_signature[i] ) {
      printf( "input file is not zip file.\n" ) ;
      fclose( fp ) ;
      return 1 ;
    }
  }

  if( fseek( fp, zip_end_header.central_dir_offset, SEEK_SET ) ) {
    printf( "failed to seek input file.\n" ) ;
    return -1 ;
  }

  printf( "this zip file includes %d files.\n", zip_end_header.number_of_entries ) ;
  for( i = 0; i < zip_end_header.number_of_entries; i++ ) {

    if( ! fread( &zip_central_header, SIZEOF_ZIP_CENTRAL_HEADER, 1, fp ) ) {
      printf( "failed to read included file[%d].\n", i ) ;
      return -1 ;
    }
    printf( "- " ) ;
    for( j = 0; j < zip_central_header.file_name_length; j++ ) {
      printf( "%c", fgetc( fp ) ) ;
    }
    for( j = 15; j > zip_central_header.file_name_length; j-- ) {
      printf( " " ) ;
    }
    printf( " %d (%d) bytes\n", zip_central_header.uncompressed_size, zip_central_header.compressed_size ) ;

    if( fseek( fp, zip_central_header.extra_field_length, SEEK_CUR ) ) {
      printf( "failed to seek included file[%d].\n", i ) ;
      return -1 ;
    } 

  }

  fclose( fp ) ;

  return 0 ;

}

